package com.yeqian.controller;

import com.yeqian.entity.Result;
import com.yeqian.pojo.Admin;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

/**
 * @Author : yeqian
 * @Date : 2020/12/25 10:08
 * 管理员控制器
 */
@RestController
@RequestMapping("/admin")
@Api(description = "管理员控制器")
public class AdminController extends BaseController {


    /**
     * 注册用户
     *
     * @param admin
     * @return com.yeqian.entity.Result
     * @author yeqian
     * @date 2021/1/14 14:31
     */
    @PostMapping("/regist")
    @ApiOperation("注册用户")
    public Result registAdmin(@RequestBody Admin admin) {
        String encode = passwordEncoder.encode(admin.getPassword());

        //设置加密后的密码
        admin.setPassword(encode);
        adminService.registAdmin(admin);
        return new Result(true, "注册用户成功");
    }

    /**
     * 查询作者名
     *
     * @param authorId
     * @return com.yeqian.entity.Result
     * @author yeqian
     * @date 2021/1/6 15:15
     */
    @GetMapping("/getAuthorName/{id}")
    @ApiOperation("查询作者名")
    public Result getAuthorName(@PathVariable("id") Integer authorId) {
        String authorName = adminService.getAuthorName(authorId);
        return new Result(true, "查询作者名成功", authorName);
    }


    /**
     * 修改管理员基本信息
     *
     * @param admin
     * @return com.yeqian.entity.Result
     * @author yeqian
     * @date 2021/1/3 17:12
     */
    @PutMapping
    @ApiOperation("修改管理员基本信息")
    public Result updateUser(@RequestBody Admin admin) {
        adminService.updateUser(admin);
        return new Result(true, "修改管理员基本信息成功");
    }

    /**
     * 获取当前管理员
     *
     * @param
     * @return com.yeqian.entity.Result
     * @author yeqian
     * @date 2020/12/30 23:11
     */
    @PostMapping
    @ApiOperation("根据用户名查询管理员")
    public Result getUserByUserName() {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Admin user = adminService.getUserByUserName(principal.getUsername());
        if (user != null) {
            String username = user.getUsername();
            return new Result(true, "获取管理员信息成功", user);
        }
        return new Result(true, "获取管理员信息失败");
    }

}
